/*
 * @Author: wangyulong
 * @Date: 2018-07-09 16:17:08
 * @Last Modified by: LIWEI
 * @Last Modified time: 2019-08-13 20:04:19
 */

<template>
    <div class="ele-common-cfg-wrap">
        <Card dis-hover class="no-border-card">
            <p slot="title">
                基础用电配置
            </p>
            <Row type="flex" justify="space-between" align="middle" class="ele-common-cfg-header">
                <Col span="24">
                    <span style="font-weight:700;font-size:14px;">房源基础用电配置</span>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item">
                <Col span="4" style="width:70px;">
                    房源电价
                </Col>
                <Col span="10">
                    <Select v-model="elePriceType">
                        <Option v-for="item in elePrice" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Col>
                <Col span="8" v-if="elePriceType == 2">
                    <InputNumber style="width:180px" v-model="elePriceValue" :min="0" :max="100"  :formatter="formatInput"/>
                        元/度
                    </InputNumber>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item">
                <Col span="4" style="width:70px;">
                    付费模式
                </Col>
                <Col span="10">
                    <Select v-model="payModesType">
                        <Option v-for="item in payModes" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Col>
                <Col span="8" v-if="payModesType == 2">
                    <Select v-model="homePayModeType" style="width:180px">
                        <Option v-for="item in homePayModes" :value="item.type" :key="item.type">{{ item.text }}</Option>
                    </Select>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item" v-show="isPostPaid">
                <Col span="4" style="width:70px;">
                    透支额度
                </Col>
                <Col span="10">
                    <InputNumber v-model="overdraftAmountValue" :min="0" :max="999" :formatter="formatInput" style="width:100%" :disabled="payModesType == 1 && !parentIsPostPaid"></InputNumber>
                </Col>
                <Col span="4" style="width:70px;">
                    度
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item" v-show="isPostPaid">
                <Col span="4" style="width:70px;">
                    断电提醒
                </Col>
                <Col span="10">
                    <Select
                        style="width: 100%;"
                        v-model="lowWarnValue"
                        :disabled="payModesType == 1 && !parentIsPostPaid">
                        <Option v-for="item in LowWarnValues" :value="item" :key="item">{{ item }}</Option>
                    </Select>
                </Col>
                <Col span="4">
                    度
                </Col>
            </Row>
            <div class="ele-common-cfg-btns">
                <Button type="ghost" size="small" @click="updateEleCfg" v-pmis="26" :loading="loading">保存修改</Button>
            </div>

            <!-- 公摊设置 -->
            <Row type="flex" justify="space-between" align="middle" class="ele-common-cfg-header">
                <Col span="24">
                    <!-- <Icon type="ios-list"></Icon> -->
                    <span style="font-weight:700;font-size:14px;">房源公摊配置</span>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item">
                <Col span="4">
                    公区电表计量方式
                </Col>
                <Col span="6">
                    <Select v-model="pool_area_type">
                        <Option v-for="item in elemeter" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item">
                <Col span="4">
                    开启公摊
                </Col>
                <Col span="6">
                    <i-switch v-model="usePool"></i-switch>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="middle" class="ele-common-cfg-item" v-if="usePool">
                <Col span="4">
                    公摊模式
                </Col>
                <Col span="6">
                    <Select v-model="poolModeType" placement="top">
                        <Option v-for="item in poorMode" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </Col>
            </Row>

            <Row type="flex" :gutter="16" align="top" class="ele-common-cfg-item" style="margin-top:10px" v-if="usePool && poolModeType==2">
                <Col span="4">
                    分摊比例
                </Col>
                <Col span="20" class="pool-percent">
                    <div class="pool-percent-wrap" v-for="item in percentRooms" :key="item.id">
                        <div class="pool-percent-item" >
                            <Icon type="person" v-if="item.leases && item.leases.length" class="has-tenant-icon"></Icon>
                            <div class="poll-percent-num">
                                房间 : <strong style="font-size:14px;"> {{item.room_name}} </strong>
                            </div>
                            <div class="poll-percent-num">
                                租客 : <strong style="font-size:14px;"> {{(item.leases && item.leases[0] && item.leases[0].tenant.name)||' 无'}} </strong>
                            </div>
                            <div class="poll-percent-num">
                                电话 : <strong style="font-size:14px;"> {{(item.leases && item.leases[0] && item.leases[0].tenant.phone) || ' 无'}} </strong>
                            </div>
                            <div class="poll-percent-num">
                                比例 : <strong style="font-size:14px;"> {{ item.leases && item.leases.length ? percent(item.percentValue,total) : ' 无'}} </strong>
                            </div>
                            <input
                                class="pool-percent-input"
                                v-model="item.percentValue"
                                placeholder="请输入公摊比例"
                                @input="handleChange"
                            />
                        </div>
                    </div>
                </Col>
            </Row>
            <div class="ele-common-cfg-btns">
                <Button type="ghost" size="small" @click="updatePoorCfg" v-pmis="26" :loading="loading">保存修改</Button>
            </div>
        </Card>

        <Card dis-hover class="no-border-card second">
            <p slot="title">
                房间自定义配置列表
                <Button type="primary"
                @click="exportList"
                class="btn-in-top-large">
                导出列表
                </Button>
            </p>

            <Table class="table" :columns="columns" :data="cfgList"/>
            <div class="cfg-note" style="margin:10px">注：标红的信息表示该设置与房源设置不一致。</div>
            <!--分页-->
            <Page :total="pageTotal"
            :page-size="pageSize"
            :current.sync="currentPage"
            show-elevator
            @on-change="getEleList"
            show-total style="text-align:center"></Page>
            <!--分页end-->
        </Card>
    </div>
</template>

<script>
import { http, api } from '@/libs/http'
import bus from '@/libs/event-bus'
import util from '@/libs/util'
import { ElemeterPayMode, LowWarnValues } from '@/libs/const'
export default {
  name: 'elemeterCommonCfg',
  props: {
    homeId: Number,
    branchId: {
      required: true
    },
    leaseType: {
      type: Number,
      required: true
    }
  },
  data () {
    return {
      LowWarnValues,
      loading: false,
      clientEleConfig: '',
      currentPayType: null, // 记录现在的支付方式
      parentIsPostPaid: false, // 默认父级付费方式为先付费

      // 电价
      elePriceType: null,
      elePriceValue: 0,
      elePrice: [],

      // 付费模式
      payModes: [],
      payModesType: null,

      homePayModes: [
        // 房源付费模式
        ElemeterPayMode.properties[ElemeterPayMode.PREPAID], // 预付费
        ElemeterPayMode.properties[ElemeterPayMode.POSTPAID] // 后付费
      ],
      homePayModeType: null,

      // 透支额度
      overdraftAmountValue: 0,
      // 断电提醒
      lowWarnValue: 0,

      parentOverdraftAmountValue: null,
      parentLowWarnValue: null,

      pool_area_type: null,
      elemeter: [
        {
          value: 2,
          label: '公区独立电表模式'
        },
        {
          value: 1,
          label: '公区总电表模式'
        }
      ],

      usePool: false,

      poolModeType: 1,
      poorMode: [
        {
          value: 1,
          label: '均摊'
        },
        {
          value: 2,
          label: '按比例分摊'
        }
      ],
      ratios: {}, // 公摊比例
      total: 1,
      columns: [
        {
          title: '房间名',
          align: 'center',
          render: (h, params) => {
            return h('span', params.row.room_name)
          }
        },
        {
          title: '电价',
          align: 'center',
          render: (h, params) => {
            return h(...this.renderStr('ele_price', params.row))
          }
        },
        {
          title: '电表付费模式',
          align: 'center',
          render: (h, params) => {
            return h(...this.renderStr('pay_type', params.row, 1))
          }
        },
        {
          title: '电表透支额度',
          align: 'center',
          render: (h, params) => {
            return h(...this.renderStr('overdraft_amount', params.row))
          }
        },
        {
          title: '断电提醒',
          align: 'center',
          render: (h, params) => {
            return h(...this.renderStr('low_warn', params.row))
          }
        }
      ],
      cfgList: [],
      currentPage: 1,
      pageTotal: 0,
      pageSize: 10,

      allRooms: []
    }
  },

  mounted () {
    this.getAllRooms()
    this.init()
    bus.$on('refresh-room' + this.homeId, this.watchRoomChange)
  },
  beforeDestroy () {
    bus.$off('refresh-room' + this.homeId, this.watchRoomChange)
  },

  watch: {
    homePayModeType (newVal, oldVal) {
      if (oldVal !== null) this.currentPayType = newVal
    },
    payModesType (newVal, oldVal) {
      if (oldVal !== null) {
        if (newVal === 1) {
          this.parentIsPostPaid ? (this.currentPayType = 2) : (this.currentPayType = 1)
          this.overdraftAmountValue = this.parentOverdraftAmountValue
          this.lowWarnValue = this.parentLowWarnValue
        } else this.currentPayType = this.homePayModeType
      }
    },
    currentPayType (newVal, oldVal) {
      if (oldVal !== null) {
        this.$Modal.warning({
          title: newVal === 2 ? '预付费切换后付费' : '后付费切换预付费',
          content:
                        newVal === 2
                          ? '<p>切换后，剩余电量及充值电量将清零。为避免影响使用，建议记录相关数据后切换</p>'
                          : '<p>切换后，如电表剩余电量不足时将自动断电。为避免影响使用，建议切换后，及时充值<p>',
          okText: '我已知悉'
        })
      }
    },
    pool_area_type (newVal, oldVal) {
      // 当计量方式变化
      if (oldVal !== null) {
        // 不为初始化数据
        this.$Modal.confirm({
          title: `切换为${newVal === 1 ? '总电表模式' : '独立电表模式'}`,
          content:
                        newVal === 1
                          ? '<p>公区总电表模式：公共电表与房间电表以串联方式连接</p><br><p>公区电表用电量=各房间用电量+公区用电量</p>'
                          : '<p>公区独立电表模式：公共电表与房间电表以并联方式连接</p><br><p>公区电表用电量=公区电表单独的用电量</p>',
          okText: '确认切换',
          cancelText: '取消',
          onCancel: () => {
            // 当点击取消的时候恢复之前的模式
            this.pool_area_type = oldVal
          }
        })
      }
    }
  },

  computed: {
    isPostPaid () {
      return (this.payModesType === 1 && !this.parentIsPostPaid) || (this.payModesType === 2 && this.homePayModeType === 1)
    },
    percentRooms () {
      if (!this.allRooms) return []
      return this.allRooms.filter(room => room.id !== room.parent_id)
    }
  },

  methods: {
    watchRoomChange () {
      this.allRooms = []
      this.getAllRooms()
    },
    getAllRooms () {
      const params = {
        with_tenant: 1
      }
      http.request(this, api.room_list, [this.homeId], params, (res, err) => {
        this.allRooms = res

        this.getPoolCfg()
      })
    },
    renderStr (key, row, type) {
      let style = {}
      let standardVal
      let storeVal
      let text
      const elemeterSetting = row.elemeter_setting || {}
      const data = {
        ele_price: this.elePriceValue,
        pay_type: this.currentPayType,
        overdraft_amount: this.overdraftAmountValue,
        low_warn: this.lowWarnValue
      }
      if (type === 1) {
        standardVal = data[key]
        storeVal = elemeterSetting[key]
        text = storeVal ? (storeVal === 1 ? '预付费' : '后付费') : '-'
      } else {
        standardVal = Number(data[key])
        storeVal = Number(elemeterSetting[key])
        text = elemeterSetting[key] ? storeVal.toFixed(4) : '-'
      }
      if (text !== '-' && standardVal !== storeVal) {
        style.color = 'red'
        style.fontWeight = '600'
      }
      return ['span', { style }, text]
    },
    formatInput (newVal) {
      if (newVal < 0) {
        return 1
      } else {
        return newVal
      }
    },
    init () {
      this.getEleCfg() // 初始化通用电表配置
      this.getEleList()
    },
    async getEleList (page) {
      if (page === 1) {
        this.currentPage = 1
      }
      const params = {
        limit: this.pageSize,
        offset: this.pageSize * (this.currentPage - 1)
      }
      const res = await http.req(api.home_elemeter_setting_list, [this.homeId], params)
      if (res) {
        this.pageTotal = res.count
        this.cfgList = res.rows.sort((a, b) => {
          return a.room_name - b.room_name || b.room_type - a.room_type || a.room_name.localeCompare(b.room_name)
        })
      }
    },
    exportList () {
      const params = {
        limit: this.pageSize,
        offset: this.pageSize * (this.currentPage - 1)
      }
      http.exportTable(this, api.home_elemeter_setting_list_export, [this.homeId], params)
    },
    getEleCfg () {
      http.request(this, api.home_elemeter_setting_info, [this.homeId], null, (res, err) => {
        let { ele_price, low_warn, overdraft_amount, pay_type } = res // 获取电价，付费模式，透支额度，断点提醒

        // 电价
        this.elePrice = []
        this.elePrice.push(
          {
            value: 1,
            label: `${this.branchId ? '门店' : '公司'}指导: ${ele_price.parent_value ? `${ele_price.parent_value}元/度` : '未知'}`
          },
          {
            value: 2,
            label: '房源自定义'
          }
        )

        if (ele_price.value) {
          // 如果存在自定义电价
          this.elePriceType = 2
          this.elePriceValue = Number(ele_price.value)
        } else {
          this.elePriceType = 1
        }

        // 透支额度
        this.parentOverdraftAmountValue = +overdraft_amount.parent_value
        this.overdraftAmountValue = Number(overdraft_amount.value || overdraft_amount.parent_value || 1)

        // 低电提醒

        this.lowWarnValue = Number(low_warn.value || low_warn.parent_value || 1)
        this.parentLowWarnValue = +low_warn.parent_value

        // 付费模式
        this.payModes = []
        this.payModes.push(
          {
            value: 1,
            label: `${this.branchId ? '门店' : '公司'}指导: ${
              pay_type.parent_value ? `${pay_type.parent_value === 1 ? '预付费' : '后付费'}` : '未知'
            }`
          },
          {
            value: 2,
            label: '房源自定义'
          }
        )

        if (pay_type.parent_value === 2) this.parentIsPostPaid = true

        if (pay_type.value) {
          // 如果存在自定义付费模式
          this.payModesType = 2
          pay_type.value === 1 ? (this.homePayModeType = 1) : (this.homePayModeType = 2)
          this.currentPayType = pay_type.value
        } else {
          this.payModesType = 1
          this.homePayModeType = 1
          this.parentIsPostPaid ? (this.currentPayType = 2) : (this.currentPayType = 1)
        }
      })
    },

    updateEleCfg () {
      let params = {}

      if (this.elePriceType === 2) {
        if (!this.elePriceValue) {
          this.$Message.info('房源电价设置错误')
          return
        }
        params.ele_price = this.elePriceValue
      }

      if (this.payModesType === 2 && this.homePayModeType) {
        params.pay_type = this.homePayModeType
      }

      if (this.payModesType === 2 && this.homePayModeType === 1) {
        if (!this.overdraftAmountValue || this.overdraftAmountValue < 0.01) {
          this.$Message.info('透支额度最少为0.01')
          return
        }
        params.overdraft_amount = +this.overdraftAmountValue.toFixed(2)
        params.low_warn = this.lowWarnValue
      }

      if (params.ele_price > 5) {
        this.$Message.info('电价设置最大不能超过5元')
        return
      }
      this.loading = true
      http.request(this, api.home_elemeter_setting_update, [this.homeId], params, (res, err) => {
        // 修改成功
        this.loading = false
        if (err) return
        this.$Message.success('用电设置保存成功!')
        this.getEleCfg()
      })
    },

    getPoolCfg () {
      http.request(this, api.home_pool_setting_info, [this.homeId], null, res => {
        // 公摊设置
        if (res) {
          this.usePool = !!res.use_pool
          this.pool_area_type = res.pool_area_type
          this.poolModeType = res.pool_type || 1
          this.ratios = res.ratios
          this.setPoolRatios(this.ratios)
        }
      })
    },
    setPoolRatios (ratios) {
      // 公摊比例回显
      this.allRooms.forEach(item => {
        item.percentValue = ratios[item.id] && ratios[item.id].ratio
      })
      this.handleChange()
    },
    handleChange () {
      let total = 0
      this.allRooms.forEach(item => {
        if (item.leases && item.leases.length && item.percentValue && Number(item.percentValue) > 0) {
          total += Number(item.percentValue)
        }
      })
      this.total = total
      util.log('change', total)
    },
    updatePoorCfg () {
      this.loading = true
      let params = {
        pool_area_type: this.pool_area_type,
        use_pool: this.usePool,
        pool_type: this.poolModeType
      }

      let ratios = {}
      this.allRooms.forEach(item => {
        if (item.percentValue) {
          ratios[item.id] = +item.percentValue
        }
      })
      params.ratios = ratios

      http.request(this, api.home_pool_setting_update, [this.homeId], params, res => {
        this.loading = false
        // 公摊设置
        if (res) this.$Message.success('公摊设置保存成功')
      })
    },
    percent (value, total) {
      let num = Number(value)
      if (isNaN(num)) {
        return '请输入数字 '
      }
      let res = (value * 100 / total || 0).toFixed(2)
      return res + ' %'
    }
  }
}
</script>

<style lang="less" scoped>
.ele-common-cfg {
    &-wrap {
        background: #fff;
        padding-bottom: 30px;
    }
    &-header {
        margin: 20px 16px 0;
        padding: 10px;
    }
    &-item {
        padding: 6px 24px;
    }
    &-btns {
        display: inline-block;
        padding: 20px 20px 0;
        margin-bottom: 30px;
    }
    &-cell-label {
        text-align: right;
    }
    &-co-wrap {
        padding-left: 100px;
    }
    &-op-wrap {
        display: inline;
        padding: 0 0 0 20px;
    }
}
.pool-percent {
    display: flex;
    flex-wrap: wrap;
    margin: 0 -10px;
    .pool-percent-wrap{
        width: 20%;
        padding: 10px;
    }

    &-input{
        width: 100%;
        height: 32px;
        padding: 0 10px;
        outline: 0;
        border-radius: 4px;
        border: 1px solid #dddee1;
    }

    .pool-percent-item {
        position: relative;
        border: 1px solid #dddee1;
        background-color: #efeff1;
        padding: 0 10px 14px;
        border-radius: 4px;
        .has-tenant-icon {
            position: absolute;
            top: 5px;
            right: 10px;
            font-size: 24px;
        }
    }
    .poll-percent-num {
        height: 20px;
        margin: 10px 0;
        padding-left: 2px;
    }
}
.ivu-card-head p {
    border-radius: 0;
}
</style>
<style lang="less">
.ele-common-cfg-wrap {
    .ivu-card-body {
        padding: 0 16px;
    }
}
.second {
    .ivu-card-body {
        padding: 16px 0;
    }
}

</style>
